import { Device, GatewayType } from "@/api/interface/iot";
import {
	addProduct,
	copyProduct,
	getProductList,
	modifyProduct,
	removeProduct,
	syncFromProduct
} from "@/api/modules/iot/product";
import notData from "@/assets/images/cube/link.png";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import SelectDeptList from "@/components/Sansan/SelectDeptList";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import BaseSearchForm from "@/components/SearchForm/BaseSearchForm";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { DeviceType, ProductStatusEnum } from "@/enums/statusEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { filePrefix } from "@/hooks/useSystem";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import { useRouter } from "vue-router";
import SaveToProduct from "./components/SaveToProduct";
import BasicDialog from "./components/basicInfo/detailDialog";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
import "./product.scss";
export default defineComponent({
	name: "ProductList",
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const router = useRouter();
		const collapsedSearch = ref<boolean>(false);
		const initParam = reactive<Device.ReqProduct>({ pageIndex: 1, pageSize: 9 });

		const dataCallback = (data: any) => {
			data.records.map((item: any) => {
				item.status = item.status + "";
				return item;
			});
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current || 1,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return getProductList(params);
		};
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			useAuthButtons().then(btnList => {
				buttonsList.value = btnList.filter((item: any) => !item.btnGroup || item.btnGroup != 3);
			});
		});
		onActivated(() => {
			proTable.value.getTableList();
		});
		const addDialog = reactive<any>({
			title: proxy?.$t("product.dialog_title.add"),
			visible: false
		});
		const clickBtn = async (fn: string, row: any) => {
			let selected: any[] = row?.selectList || [row];
			switch (fn) {
				case "details":
					if (selected.length != 1) {
						showMsg(proxy?.$t("product.msg.details"), MessageType.warning);
						return;
					}
					router.push({
						path: RouterPath.productDetail,
						query: { id: selected[0].id }
					});
					break;
				case "mod":
					if (selected.length != 1) {
						showMsg(proxy?.$t("product.msg.mod"), MessageType.warning);
						return;
					}
					detail.value = { ...selected[0] };
					addDialog.visible = true;
					break;
				case "add":
					//默认为软产品
					detail.value = { deviceType: GatewayType.Device };
					addDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("product.msg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("product.confirm.del") }).then(flag => {
						flag && submitDel({ id: selected.map(item => item.id).join(",") });
					});
					break;
				case "copy":
					if (selected.length != 1) {
						showMsg(proxy?.$t("product.msg.copy"), MessageType.warning);
						return;
					}
					copyProductDialog.visible = true;
					copyProductDialog.formData = JSON.parse(JSON.stringify(selected[0]));
					// copyProductDialog.formData.id = selected[0].model;
					break;
				case "syncFromProduct":
					if (selected.length != 1) {
						showMsg(proxy?.$t("product.msg.syncFromProduct"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("product.confirm.syncFromProduct") }).then(flag => {
						if (!flag) {
							return;
						}
						syncFromProduct({ productModel: selected[0].model }).then(({ code }) => {
							let ok = showTips(code, proxy?.$t("product.tips.syncFromProduct"));
							if (ok) {
								proTable.value.getTableList();
							}
						});
					});
					break;
			}
		};

		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "model", label: proxy?.$t("product.tablist_label.model"), search: { el: "input" } },
			{ prop: "name", label: proxy?.$t("product.tablist_label.name"), search: { el: "input" } },
			// { prop: "status", label: "产品状态", search: { slot: {} } },
			{ prop: "deviceType", label: proxy?.$t("product.tablist_label.device_type"), search: { slot: {} } },
			{ prop: "deptName", label: proxy?.$t("product.tablist_label.dept_name"), search: { slot: {} } },
			{ prop: "descript", label: proxy?.$t("product.tablist_label.descript") },
			{ prop: "createTime", label: proxy?.$t("product.tablist_label.create_time"), width: "180" },
			{ prop: "operation", label: proxy?.$t("product.tablist_label.operation"), fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const detail = ref<any>({});
		const submitDel = async (dataInfo: any) => {
			let res = await removeProduct({ ...dataInfo });
			let ok = showTips(res.code, proxy?.$t("product.tips.remove"), res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submitAdd = async () => {
			detail.value.model = detail.value.model.trim();
			detail.value.name = detail.value.name || detail.value.model;

			let api = detail.value.id ? modifyProduct : addProduct;
			let res = await api({ ...detail.value });
			let ok = showTips(res.code, proxy?.$t("product.tips.add"), res.message);
			if (ok) {
				addDialog.visible = false;
				proTable.value.clearSelection();
				proTable.value.getTableList();
			}
		};
		const copyProductDialog = reactive<any>({
			visible: false,
			formData: {}
		});
		const submitCopyProduct = async (data: Device.ReqProduct) => {
			// let newProduct = { ...copyProductDialog.formData };
			// newProduct.model = data.productModel;
			// newProduct.name = data.productName;
			// delete newProduct.id;
			let { code, message } = await copyProduct(data);
			let ok = showTips(code, proxy?.$t("product.tips.copy"), message);
			if (ok) {
				copyProductDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		return () => {
			return (
				<div>
					<BasicDialog
						width="800px"
						title={addDialog.title}
						v-model:visible={addDialog.visible}
						detail={detail.value}
						onSubmit={() => submitAdd()}
					></BasicDialog>
					<SaveToProduct
						title={proxy?.$t("product.dialog_title.copy")}
						v-model:visible={copyProductDialog.visible}
						formData={copyProductDialog.formData}
						onSubmit={(data: Device.ReqProduct) => submitCopyProduct(data)}
					></SaveToProduct>
					{collapsedSearch.value ? null : (
						<BaseSearchForm class="mb-2">
							<el-form
								class="flex pt-4 pl-4 pr-4 bg-white"
								style="flex-wrap: wrap;"
								onKeyup={(e: KeyboardEvent) => (e.keyCode == 13 ? proTable.value.getTableList() : null)}
							>
								<el-form-item class="search-item" label={proxy?.$t("product.search_label.deptName")}>
									<div style="width:180px">
										<SelectDeptList detail={initParam} appendChild />
									</div>
								</el-form-item>
								<el-form-item class="search-item" label={proxy?.$t("product.search_label.name")}>
									<el-input
										v-model={initParam.name}
										placeholder={proxy?.$t("product.search_placeholder.name")}
										style="width:130px"
									/>
								</el-form-item>
								<el-form-item class="search-item" label={proxy?.$t("product.search_label.model")}>
									<el-input
										v-model={initParam.model}
										placeholder={proxy?.$t("product.search_placeholder.model")}
										style="width:130px"
									/>
								</el-form-item>
								<el-form-item class="search-item" label={proxy?.$t("product.search_label.deviceType")}>
									<el-select v-model={initParam.deviceType} style="width:100px">
										<el-option label={proxy?.$t("product.option.all")} value=""></el-option>
										<el-option label={proxy?.$t("product.option.device")} value={GatewayType.Device}></el-option>
										<el-option label={proxy?.$t("product.option.softgateway")} value={GatewayType.SoftGateway}></el-option>
										<el-option label={proxy?.$t("product.option.gateway")} value={GatewayType.Gateway}></el-option>
									</el-select>
								</el-form-item>
								<el-form-item class="search-item">
									<el-button type="primary" class="iconfont iconsearch" onClick={() => proTable.value.getTableList()}>
										{proxy?.$t("common.btn.search")}
									</el-button>
									<el-button
										class="iconfont iconsearch"
										onClick={() => {
											for (let key in initParam) {
												initParam[key] = null;
											}
											// proTable.value.getTableList();
										}}
									>
										{proxy?.$t("common.btn.reset")}
									</el-button>
								</el-form-item>
							</el-form>
						</BaseSearchForm>
					)}
					<ProTable
						ref={proTable}
						custSearch
						onSearchCollapsed={val => {
							collapsedSearch.value = val;
						}}
						ignoreInit
						title={buttonsList.value.length ? "" : proxy?.$t("product.tab_title.manage")}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
						searchCol={5}
						toolbar={["grid"]}
						viewType="grid"
						gridSpan={8}
					>
						{{
							"search-status": () => {
								return (
									<el-select v-model={initParam.status} style="width:100px">
										<el-option label={proxy?.$t("product.option.all")} value=""></el-option>
										<el-option label={ProductStatusEnum.DEPLOY_LABEL} value={ProductStatusEnum.DEPLOY}></el-option>
										<el-option label={ProductStatusEnum.DEVELOP_LABEL} value={ProductStatusEnum.DEVELOP}></el-option>
									</el-select>
								);
							},
							"search-deviceType": () => {
								return (
									<el-select v-model={initParam.deviceType} style="width:100px">
										<el-option label={proxy?.$t("product.option.all")} value=""></el-option>
										<el-option label={proxy?.$t("product.option.device")} value={GatewayType.Device}></el-option>
										<el-option label={proxy?.$t("product.option.softgateway")} value={GatewayType.SoftGateway}></el-option>
										<el-option label={proxy?.$t("product.option.gateway")} value={GatewayType.Gateway}></el-option>
									</el-select>
								);
							},
							"search-deptName": () => {
								return <SelectDeptList detail={initParam} appendChild onChange={val => (initParam.deptId = val.id)} />;
							},
							tableHeader: (scope: any) => {
								return buttonsList.value?.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								});
							},
							cardBody: (scope: any) => {
								return (
									<div class="product-card">
										<div class="bg"></div>
										<div class="product-container">
											<div class="master-row flex items-center pt-8 pl-8 pr-8">
												<div class="product-img pr-4">
													<el-image
														fit="fill"
														class="product-icon img"
														src={scope.row.photo ? `${filePrefix()}${scope.row.photo}` : notData}
													/>
												</div>
												<div class="product-name flex-1 overflow">
													<div class="text-lg font-bold">{scope.row.name}</div>
													<div class="time text text-sm text-gray-500 leading-7">
														<span>{proxy?.$t("product_card.label.created_time")}</span>
														<span>{dataFormat("datetime", scope.row.createTime)}</span>
													</div>
												</div>
												{buttonsList.value.find((item: any) => item.path == "del" || item.path == "mod") ? (
													<div style="margin-top: -25px;">
														<el-dropdown
															v-slots={{
																dropdown: () => {
																	return (
																		<el-dropdown-menu>
																			{buttonsList.value.find((item: any) => item.path == "mod") ? (
																				<el-dropdown-item onClick={() => clickBtn("mod", scope.row)}>
																					{proxy?.$t("product_card.dropdpwn_btn.edit")}
																				</el-dropdown-item>
																			) : null}
																			{buttonsList.value.find((item: any) => item.path == "del") ? (
																				<el-dropdown-item onClick={() => clickBtn("del", scope.row)}>
																					{proxy?.$t("product_card.dropdpwn_btn.delete")}
																				</el-dropdown-item>
																			) : null}
																		</el-dropdown-menu>
																	);
																}
															}}
														>
															<el-link underline={false}>
																<i class="iconfont iconmore-vertical" style="font-size:22px" />
															</el-link>
														</el-dropdown>
													</div>
												) : null}
											</div>
											<div class="body pt-6">
												<div class="grid grid-cols-3 pl-8 pr-8">
													<div class="flex col-span-2">
														<div class="label">{proxy?.$t("product_card.label.model")}</div>
														<div class="text">{scope.row.model || "--"}</div>
													</div>
													<div class="flex">
														<div class="label">{proxy?.$t("product_card.label.deviceType")}</div>
														<div class="text">{DeviceType[scope.row.deviceType]}</div>
													</div>
													<div class="col-span-3 flex">
														<div class="label">{proxy?.$t("product_card.label.description")}</div>
														<div class="text">{scope.row.description || "--"}</div>
													</div>
												</div>
												<div class="flex pt-6 pl-8 pr-8 ">
													<el-button type="primary" onClick={() => clickBtn("details", scope.row)}>
														{proxy?.$t("product_card.btn.detail")}
														<i class="iconfont iconbx-right-arrow-alt ml-1"></i>
													</el-button>
												</div>
											</div>
										</div>
									</div>
								);
							},
							status: (scope: any) => {
								return (
									<OnlineStatus
										v-model={scope.row.status}
										onlineLabel={ProductStatusEnum.DEPLOY_LABEL}
										offlineLabel={ProductStatusEnum.DEVELOP_LABEL}
									/>
								);
							},
							model: (scope: any) => {
								return (
									<div class="truncate cursor-pointer primary-color" onClick={() => clickBtn("details", scope.row)}>
										{scope.row.model}
									</div>
								);
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							operation: (scope: any) => {
								return (
									<>
										{buttonsList.value
											.filter((item: any) => item.path == "del")
											.map((item: any) => {
												return (
													<el-popconfirm
														title={proxy?.$t("product.confirm_title.del")}
														popper-class="jsonform-tooltip"
														onConfirm={() => submitDel({ id: scope.row.id })}
													>
														{{
															reference: () => {
																return (
																	<el-link type="danger">
																		<i class="iconfont icontrash-2"></i>
																		{item.menuName}
																	</el-link>
																);
															}
														}}
													</el-popconfirm>
												);
											})}
										{!buttonsList.value.find((item: any) => item.path == "del") ? (
											<el-link type="danger" disabled>
												<i class="iconfont icontrash-2"></i>
												{proxy?.$t("product.btn.delete")}
											</el-link>
										) : null}
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("details", scope.row);
											}}
										>
											{proxy?.$t("product.btn.detail")}
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<div>
										<Empty
											class="text-left leading-6"
											subtitle={proxy?.$t("product.empty.subtitle")}
											btnText={proxy?.$t("product.empty.btntext")}
											showButton={buttonsList.value.some((item: any) => item.path == "add")}
											onAdd={() => {
												clickBtn("add", {});
											}}
										/>
									</div>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
